package brackets

import (
	C "gitee.com/ljfirst/algo-go-sdk/common/constant"
	"gitee.com/ljfirst/algo-go-sdk/tools"
)

/**
 * @author ljfirst
 * @version V1.0
 * @date 2023/9/8 12:27
 * @author-Email ljfirst@mail.ustc.edu.cn
 * @blogURL https://blog.csdn.net/ljfirst
 * @description
 **/
type LongestEffectBrackets struct {
}

func (m *LongestEffectBrackets) Method(str string) int {
	if len(str) == 0 {
		return 0
	}
	best := 0
	bestTemp := 0
	stack := make([]int, 0)
	for i, s := range str {
		if s-')' == 0 {
			if len(stack) != 0 && str[stack[len(stack)-1]] == '(' {
				bestTemp = i - stack[len(stack)-1]
				best = tools.Max(best, bestTemp+1)
				stack = stack[0 : len(stack)-1]
				if len(stack) == 0 { // 当栈为空，说明截止目前的都是有效括号
					best = tools.Max(best, i+1)
				}
				continue
			}
		}
		stack = append(stack, i)
	}
	res := 0
	if len(stack) != 0 { // 当栈不为空，说明最后一个栈元素以后的都是有效括号
		res = len(str) - 1 - stack[len(stack)-1]
		return tools.Max(best, res)
	} else {
		return len(str) // 当栈为空，说明截止目前的都是有效括号
	}
}

func (m *LongestEffectBrackets) GetAttribute() *C.Attribute {
	return &C.Attribute{
		Tags: []string{},
		Desc: &C.Desc{
			Name:        "LongestEffectBrackets",
			NameCn:      "最长有效括号",
			Description: "",
			ParamsDesc: map[string]string{
			},
			Example: map[int]string{
			},
		},
	}
}
